<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>Papers</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f5f5f5;
            font-family: 'Arial', sans-serif;
            color: #333;
            font-size: 16px;
        }

        h2 {
            color: #004d99;
            text-align: center;
            margin-top: 30px;
            margin-bottom: 20px;
            letter-spacing: 1px;
        }

        .container {
            max-width: 1200px;
            margin: auto;
            padding: 20px;
        }

        .card {
            margin-bottom: 20px;
            transition: box-shadow 0.3s;
            border-radius: 12px;
        }

        .card:hover {
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
        }

        .abstract {
            cursor: pointer;
            max-height: 50px;
            overflow: hidden;
            transition: max-height 0.3s ease-out;
            position: relative;
        }

        .abstract::after {
            content: "+";
            position: absolute;
            top: 50%;
            right: 0;
            transform: translateY(-50%);
            transition: transform 0.3s;
        }

        .abstract.expanded {
            max-height: none;
        }

        .abstract.expanded::after {
            content: "-";
            transform: translateY(-50%) rotate(180deg);
        }

        .abstract .content {
            white-space: pre-wrap;
            font-size: 0.95em;
            color: #555;
        }

        .search-bar {
            margin-bottom: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .search-bar .form-control {
            width: 400px;
            margin-right: 10px;
            border-radius: 20px;
            padding-left: 15px;
            box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
            transition: box-shadow 0.3s;
        }

        .search-bar .form-control:focus {
            box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.2);
        }

        .btn-primary {
            background-color: #004d99;
            border-color: #004d99;
            transition: all 0.3s ease;
            font-weight: 600;
            letter-spacing: 1px;
        }

        .btn-primary:hover {
            background-color: #003c80;
            border-color: #003c80;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 20px;
        }

        .pagination button {
            margin: 0 5px;
            padding: 0.6rem 1.2rem;
            font-size: 1rem;
            border-radius: 20px;
            transition: background-color 0.3s, transform 0.3s;
            background-color:#0056b3;
            color:white;
            border: none;
        }

        .pagination button:hover {
            background-color: #004494;
            transform: translateY(-1px);
        }

        .pagination button:disabled {
            background-color: #007bff;
            cursor: not-allowed;
        }

        .sort-select {
            margin-bottom: 20px;
            max-width: 200px;
            margin: auto;
        }

        .form-control.mt-2 {
            margin-top: 10px;
        }

        .add-paper-form {
            max-width: 600px;
            margin: 30px auto;
            padding: 15px;
            background-color: #fff;
            border-radius: 15px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .add-paper-form input,
        .add-paper-form textarea {
            margin-bottom: 15px;
        }

        .row {
            margin-top: 30px;
        }

        .col-md-4 {
            display: flex;
            justify-content: center;
        }
    </style>
</head>

<body>
<div class="container">
    <h2>论文列表</h2>

    <!-- 新增论文 -->
    <div class="add-paper-form">
        <h5 class="text-center">新增一篇论文</h5>
        <input type="text" id="newPaperTitle" class="form-control" placeholder="请输入论文标题" required>
        <input type="text" id="newPaperAuthor" class="form-control" placeholder="请输入作者名字" required>
        <textarea id="newPaperAbstract" class="form-control" placeholder="请输入论文摘要" required></textarea>
        <input type="text" id="newPaperDownloadLink" class="form-control" placeholder="请输入论文链接" required>
        <button class="btn btn-primary w-100" onclick="addPaper()">新增论文</button>
    </div>

    <!-- Search Bar -->
    <div class="search-bar">
        <input type="text" id="searchInput" class="form-control" placeholder="请根据标题和作者搜索">
        <button class="btn btn-primary" onclick="searchPapers()">搜索</button>
    </div>

    <!-- Sorting Controls -->
    <select class="form-select sort-select" onchange="sortPapers(this.value)">
        <option value="title">按标题排序</option>
        <option value="author">按作者排序</option>
    </select>

    <!-- Pagination Controls -->
    <div class="pagination">
        <button class="btn btn-secondary" onclick="previousPage()" disabled>前一页</button>
        <span id="currentPage" class="mx-2">1</span>
        <button class="btn btn-secondary" onclick="nextPage()">下一页</button>
    </div>

    <!-- Cards for Papers -->
    <div id="papersCards" class="row">
        <div class="col-md-4" th:each="paper, iterStat : ${papers}">
            <div class="card" style="width: 128rem;">
                <div class="card-body">
                    <h5 class="card-title" th:text="${paper.title}">Title</h5>
                    <h6 class="card-subtitle mb-2 text-muted" th:text="${paper.author}">Author</h6>
                    <div class="abstract">
                        <div class="content" th:text="${paper.abstractText}">Abstract</div>
                    </div>
                    <a th:href="${paper.downloadLink}" class="btn btn-primary mt-2">下载</a>
                    <button class="btn btn-danger mt-2" th:attr="onclick=|deletePaper(${paper.id})|">删除</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    let currentPage = 1;
    const itemsPerPage = 6; // 每页显示的卡片数量
    let papersData = []; // 存储原始数据

    // 初始化数据
    document.querySelectorAll('#papersCards .card').forEach((card, index) => {
        papersData.push({
            card: card,
            title: card.querySelector('.card-title').textContent,
            author: card.querySelector('.card-subtitle').textContent,
            abstract: card.querySelector('.abstract .content').textContent
        });
    });

    // 显示当前页的数据
    function showPage(page) {
        const start = (page - 1) * itemsPerPage;
        const end = start + itemsPerPage;
        const cards = document.querySelectorAll("#papersCards .card");

        cards.forEach((card, index) => {
            if (index >= start && index < end) {
                card.style.display = "";
            } else {
                card.style.display = "none";
            }
        });

        document.getElementById('currentPage').innerText = page;
        updatePaginationButtons(); // 更新分页按钮状态
    }

    // 下一页
    function nextPage() {
        const cards = document.querySelectorAll("#papersCards .card");
        if ((currentPage * itemsPerPage) < cards.length) {
            currentPage++;
            showPage(currentPage);
        }
    }

    // 上一页
    function previousPage() {
        if (currentPage > 1) {
            currentPage--;
            showPage(currentPage);
        }
    }

    // 初始化分页
    showPage(currentPage);

    // 搜索功能
    function searchPapers() {
        const input = document.getElementById("searchInput").value.toLowerCase();
        const filteredPapers = papersData.filter(paper =>
            paper.title.toLowerCase().includes(input) ||
            paper.author.toLowerCase().includes(input)
        );

        const papersContainer = document.querySelector('#papersCards');
        papersContainer.innerHTML = '';

        if (filteredPapers.length === 0) {
            const noResultsMessage = document.createElement('p');
            noResultsMessage.textContent = '没有找到相关论文';
            noResultsMessage.style.textAlign = 'center';
            noResultsMessage.style.color = '#999';
            papersContainer.appendChild(noResultsMessage);
        } else {
            filteredPapers.forEach((paper, index) => {
                const card = paper.card.cloneNode(true);
                papersContainer.appendChild(card);
            });
        }

        currentPage = 1;
        showPage(currentPage);
    }

    // 排序功能
    function sortPapers(field) {
        const visiblePapers = Array.from(document.querySelectorAll('#papersCards .card'))
            .map(card => ({
                card,
                title: card.querySelector('.card-title').textContent,
                author: card.querySelector('.card-subtitle').textContent
            }));

        visiblePapers.sort((a, b) => {
            const valA = field === 'title' ? a.title : a.author;
            const valB = field === 'title' ? b.title : b.author;
            return valA.localeCompare(valB);
        });

        document.querySelector('#papersCards').innerHTML = '';
        visiblePapers.forEach(paper => {
            document.querySelector('#papersCards').appendChild(paper.card);
        });

        currentPage = 1;
        showPage(currentPage);
    }

    // 抽屉效果
    document.querySelectorAll('.abstract').forEach(abstract => {
        abstract.addEventListener('click', function() {
            this.classList.toggle('expanded');
            const content = this.querySelector('.content');
            content.style.maxHeight = this.classList.contains('expanded') ? content.scrollHeight + "px" : "50px";
        });
    });

    // 更新分页按钮状态
    function updatePaginationButtons() {
        const prevButton = document.querySelector('.pagination .btn-secondary:first-child');
        const nextButton = document.querySelector('.pagination .btn-secondary:last-child');

        prevButton.disabled = currentPage === 1;
        nextButton.disabled = (currentPage * itemsPerPage) >= document.querySelectorAll('#papersCards .card').length;
    }

    // 删除论文
    function deletePaper(id) {
        if (confirm('您确定要删除这篇论文吗？')) {
            fetch('http://localhost:8080/papers/' + id, {
                method: 'DELETE'
            }).then(response => {
                if (response.ok) {
                    alert('论文删除成功');
                    window.location.reload(); // 刷新页面
                } else {
                    alert('删除论文失败');
                }
            }).catch(err => {
                console.error(err);
                alert('删除论文时发生错误');
            });
        }
    }

    // 添加新论文
    function addPaper() {
        const title = document.getElementById("newPaperTitle").value;
        const author = document.getElementById("newPaperAuthor").value;
        const abstractText = document.getElementById("newPaperAbstract").value;
        const downloadLink = document.getElementById("newPaperDownloadLink").value;

        const newPaper = { title, author, abstractText, downloadLink };

        fetch('http://localhost:8080/papers', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(newPaper)
        }).then(response => {
            if (response.ok) {
                alert('论文新增成功');
                window.location.reload(); // 刷新页面
            }
        });
    }
</script>

</body>
</html>
